import { ref } from 'vue';
import { isEmpty, toast } from '@/assets/js/utils';
import { formatVoiceRecognizeCode } from '@/assets/js/utils/filters';
import { useTranslateLangStore } from '@/stores/translateLang';
import { voiceRecognize } from '@/api/translate';
import { config } from '@/assets/js/config';
import { requestAndroidPermission, gotoAppPermissionSetting } from '@/assets/js/utils/permission.js';

export function useVoiceRecognize() {
    // 是否授权录音
    const recordAuth = ref(false);
    // 通用录音管理对象
    const recorderManager = uni.getRecorderManager();
    let recorderTimer: any = null; // 录制时长计时器
    const recorderDuration = ref(30); //录音最大值，单位秒
    const recorderCount = ref(0); // 录制倒计时
    const voiceRecognizeStatus = ref(1); // 1初始状态 2语音录入中 3语音识别中

    // 微信小程序环境-中文录音识别管理对象
    let zhRecorderManager = null;
    // #ifdef MP-WEIXIN
    const plugin = requirePlugin('WechatSI');
    zhRecorderManager = plugin.getRecordRecognitionManager();
    // #endif

    // // #ifndef MP-WEIXIN
    // console.log('其他环境');
    // // #endif
    //开始识别
    const startVoiceRecognize = async () => {
        return <any>new Promise(async (resolve, reject) => {
            //判断录音是否授权，实时获取解决用户半途取消录音权限或者录音权限异常回收问题
            // #ifdef MP-WEIXIN
            // !recordAuth.value && (await appAuthorRecord());
            //
            await authorRecord()
            // #endif
            // #ifndef MP-WEIXIN
            // !recordAuth.value && (await appAuthorRecord());
            await appAuthorRecord()
            // #endif
            if (!recordAuth.value) {
                resolve([null, '录音未授权']);
                return;
            }
            //录制中再次点击手动关闭录制
            if (voiceRecognizeStatus.value == 2 || voiceRecognizeStatus.value == 3) {
                endVoiceRecognize();
            }
            // 清除播放时间
            clearInterval(recorderTimer);
            // 开始倒计时
            countdown(recorderDuration.value);
            voiceRecognizeStatus.value = 2;
            if (useTranslateLangStore().sourceLang == 'zh' && !isEmpty(zhRecorderManager)) {
                //微信小程序插件录音器 - 中文识别
                zhRecorderManager.onStart = (result: any) => {
                    console.log('中文开始录制', result);
                };
                zhRecorderManager.onError = (err: any) => {
                    voiceRecognizeStatus.value = 1;
                    resolve([null, formatVoiceRecognizeCode(err.retcode)]);
                    console.log(`中文录制错误：${JSON.stringify(err)}`);
                };
                //识别结束
                zhRecorderManager.onStop = (result: any) => {
                    voiceRecognizeStatus.value = 1;
                    if (result.result && !isEmpty(result.result)) {
                        let recognizeText = result.result.replace(/。$/, '');
                        resolve([recognizeText, null]);
                        // translateResult.value = {};
                        // startTranslating();
                    } else {
                        resolve([null, `未识别到语音`]);
                        toast('未识别到语音');
                    }
                };
                //识别开始
                zhRecorderManager.start({ duration: recorderDuration.value * 1000, lang: 'zh_CN' });
            } else {
                //uni录音器
                recorderManager.onStart(result => {
                    console.log(`${useTranslateLangStore().sourceLang}开始录制`, JSON.stringify(result));
                });
                recorderManager.onError(result => {
                    voiceRecognizeStatus.value = 1;
                    resolve([null, '请说出想翻译的话']);
                    console.log(`${useTranslateLangStore().sourceLang}录制错误：${JSON.stringify(result)}`);
                });
                //uni录音器识别结束
                recorderManager.onStop(async res => {
                    console.log(`${useTranslateLangStore().sourceLang}结束录制`, JSON.stringify(res));
                    // 录音结束，上传最新的录音
                    let [result, err] = await voiceRecognize(res.tempFilePath, useTranslateLangStore().sourceLang == 'zh' ? 1 : 2);
                    voiceRecognizeStatus.value = 1;
                    console.log(result);
                    if (result) {
                        if(useTranslateLangStore().sourceLang == 'zh') {
                            let resultData = JSON.parse(result);
                            if(resultData && resultData.text) {
                                resolve([resultData.text, null]);
                            }else{
                                resolve([null, '没有听清，请再说一次~']);
                            }
                        }else{
                            resolve([result, null]);
                        }
                    } else {
                        resolve([null, err]);
                    }
                });
                //uni录音器识别开始
                recorderManager.start({
                    duration: recorderDuration.value * 1000, // 指定录音的时长，单位 ms
                    sampleRate: 16000, // 采样率
                    numberOfChannels: 1, // 录音通道数
                    format: 'wav' // 音频格式，有效值 aac/mp3
                });
            }
        });
    };
    //结束识别
    const endVoiceRecognize = () => {
        //只有录音状态才能结束识别
        if (voiceRecognizeStatus.value == 2) {
            voiceRecognizeStatus.value = 3;
            clearInterval(recorderTimer);
            if (useTranslateLangStore().sourceLang == 'zh' && zhRecorderManager) {
                zhRecorderManager.stop();
            } else {
                recorderManager.stop();
            }
        }
    };

    // 倒计时
    const countdown = (val: any) => {
        recorderCount.value = Number(val);
        recorderTimer = setInterval(() => {
            if (recorderCount.value > 0) {
                recorderCount.value--;
            } else {
                endVoiceRecognize();
            }
        }, 1000);
    };

    //判断录音权限是否授权
    const authorRecord = () => {
        return new Promise((resolve, reject) => {
            uni.authorize({
                scope: 'scope.record', //这里选择scope.(录音、位置、用户信息...都可以)
                success() {
                    // 允许授权
                    resolve(true);
                    console.log('已授权');
                    recordAuth.value = true;
                },
                fail() {
                    // 拒绝授权
                    uni.showModal({
                        content: '检测到您没打开录音功能权限，是否去设置打开？',
                        confirmText: '确认',
                        confirmColor: '#1874f5',
                        cancelText: '取消',
                        success: res => {
                            if (res.confirm) {
                                uni.openSetting({
                                    // opensetting 是调起设置页面的
                                    success: res => {
                                        // 获取设置授权的状态
                                        const setting = res.authSetting;
                                        recordAuth.value = setting['scope.record'] || false;
                                    }
                                });
                            } else {
                                reject(false);
                                return false;
                            }
                        }
                    });
                    reject(false);
                    return false;
                }
            });
        });
    };
    //app端判断是否拥有录音权限
    const appAuthorRecord = () => {
        return new Promise(async (resolve, reject) => {
            var result = await requestAndroidPermission('android.permission.RECORD_AUDIO');
            if (result == 1) {
                // 允许授权
                resolve(true);
                console.log('已授权');
                recordAuth.value = true;
            } else {
                // 拒绝授权
                uni.showModal({
                    content: '检测到您没打开录音功能权限，是否去设置打开？',
                    confirmText: '确认',
                    confirmColor: '#1874f5',
                    cancelText: '取消',
                    success: res => {
                        if (res.confirm) {
                            gotoAppPermissionSetting();
                        } else {
                            reject(false);
                            return false;
                        }
                    }
                });
                reject(false);
                return false;
            }
        });
    };

    return { startVoiceRecognize, endVoiceRecognize, recorderCount, voiceRecognizeStatus, recordAuth };
}
